package com.haiyou.data.common.persister.mysql.help.invoke;

import com.haiyou.common.entity.Entity;
import com.haiyou.data.common.persister.mysql.help.ColumnHelper;
import com.haiyou.data.common.persister.mysql.meta.ColumnMeta;

public class DatetimeHelper implements InvokeHelper {

	@Override
	public void invoke(ColumnMeta columnMeta, Object ov, Entity<?> entity) {

		// TODO mysql-connector-java-8.0 取出来就是localDateTime
		java.time.LocalDateTime v = (java.time.LocalDateTime) ov;

		try {

			if (ColumnHelper.getGenericType(columnMeta) == java.time.LocalDateTime.class) {

				ColumnHelper.getSetter(columnMeta).invoke(entity, v);

			} else if (ColumnHelper.getGenericType(columnMeta) == java.util.Date.class) {

				ColumnHelper.getSetter(columnMeta).invoke(entity,
						java.util.Date.from(v.atZone(java.time.ZoneId.systemDefault()).toInstant()));

			} else if (ColumnHelper.getGenericType(columnMeta) == java.sql.Date.class) {

				ColumnHelper.getSetter(columnMeta).invoke(entity, java.sql.Date.valueOf(v.toLocalDate()));

			} else if (ColumnHelper.getGenericType(columnMeta) == java.sql.Timestamp.class) {

				ColumnHelper.getSetter(columnMeta).invoke(entity,
						java.sql.Timestamp.from(v.atZone(java.time.ZoneId.systemDefault()).toInstant()));

			} else {
				throw new RuntimeException("unknown:" + columnMeta);
			}
		} catch (Exception e) {

			throw new RuntimeException(e.getMessage() + ":" + ov + ",\n" + entity + ",\n" + columnMeta, e);

		}
	}

}
